package com.redijedi.tapestry5.internal;

import java.util.Map;

import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.ValueEncoder;

import com.redijedi.tapestry5.TreeModel;
import com.redijedi.tapestry5.TreeNodeModel;

/**
 * @author torr
 * 
 */
public class TreeModelRenderer {

	private final MarkupWriter _writer;

	@SuppressWarnings("all")
	private final ValueEncoder _encoder;

	public TreeModelRenderer(MarkupWriter writer) {
		_writer = writer;
		_encoder = null;
	}

	@SuppressWarnings("all")
	public TreeModelRenderer(MarkupWriter writer, ValueEncoder encoder) {
		_writer = writer;
		_encoder = encoder;
	}

	public void beginContainer(TreeModel treeModel) {
		_writer.element("div");
		// _writer.element("div", "id", treeModel.getId());
		writeAttributes(treeModel.getAttributes());
	}

	public void beginDiv() {
		_writer.element("div");
	}

	public void beginTree(TreeModel treeModel) {
		_writer.element("ul");
	}

	public void beginNode(TreeNodeModel treeNodeModel) {
		if (treeNodeModel == null) {
			return;
		}
		String clientValue = getClientValue(treeNodeModel);
		_writer.element("li", "id", clientValue);
		writeAttributes(treeNodeModel.getAttributes());
	}

	public void endNode() {
		_writer.end();
	}

	public void endTree() {
		_writer.end();
	}

	public void endDiv() {
		_writer.end();
	}

	public void endContainer() {
		_writer.end();
	}

	private void writeAttributes(Map<String, String> attributes) {
		if (attributes == null) {
			return;
		}
		for (Map.Entry<String, String> e : attributes.entrySet()) {
			_writer.attributes(e.getKey(), e.getValue());
		}
	}

	@SuppressWarnings("unchecked")
	private String getClientValue(TreeNodeModel treeNodeModel) {
		if (treeNodeModel == null) {
			return "";
		}
		Object nodeValue = treeNodeModel.getValue();
		if (_encoder != null) {
			return _encoder.toClient(nodeValue);
		} else {
			return InternalUtils.convertStringToIdentifier(treeNodeModel
					.getId());
		}
	}

}
